//
//  zteQhdPlugin.m
//  govcarmanage
//
//  Created by jiacheng wang on 2017/6/12.
//
//

#import "zteQhdPlugin.h"
#import "UIView+Toast.h"
#import "MRProgressOverlayView.h"
#import "AFNetworking.h"
#import "MainViewController.h"
#import <AVFoundation/AVCaptureDevice.h>
//#import <AssetsLibrary/ALAssetsLibrary.h>
#import <Photos/PHPhotoLibrary.h>

@implementation ZTEImagePicker
@end

@implementation ZTERSKImageCropViewController
@end

@implementation zteQhdPlugin
{
    MRProgressOverlayView *progressView;
}

/**
 *
 **/
- (void)getAuthInfo:(CDVInvokedUrlCommand*)command
{
    
    NSString* callbackId = command.callbackId;
    
    NSString *type = [command.arguments objectAtIndex:0];
    NSString *backVal=nil;
    
    if([type isEqualToString:@"photo"]){
        
        PHAuthorizationStatus author=[PHPhotoLibrary authorizationStatus];
        
        if(author == PHAuthorizationStatusDenied){
            
            backVal=@"0";
        }else{
            backVal=@"1";
        }
        
    }else{
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        
        if(authStatus == AVAuthorizationStatusDenied){
            backVal=@"0";
        }else{
            backVal=@"1";
        }
        
    }
    
    
    CDVPluginResult* pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:backVal];
    
    [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
    
}

/**
 *
 **/
- (void)showMainApp:(CDVInvokedUrlCommand*)command
{
    
    NSString* callbackId = command.callbackId;
    
    
    
    CDVPluginResult* pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];
    
    [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
    
}

- (void)isClickNotifi:(CDVInvokedUrlCommand*)command
{
    
    NSString* callbackId = command.callbackId;
    
    MainViewController *viewControl = (MainViewController *)[self viewController];
    CDVPluginResult* pluginresult=nil;
    if(viewControl.clickMess == nil){
        
        pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:[[NSArray alloc]
                                                                                             initWithObjects: @"",nil]];
    }else{
        NSString * url=[viewControl.clickMess valueForKey:@"url"];
        NSString * type=[viewControl.clickMess valueForKey:@"type"];
        
        pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:[[NSArray alloc]
                                                                                                              initWithObjects: url,type,nil]];
        viewControl.clickMess=nil;
    }
    
    
    [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
    
}

/**
 *
 **/
- (void)toast:(CDVInvokedUrlCommand*)command
{
    
    NSString* callbackId = command.callbackId;
    
    NSString *toastName = [command.arguments objectAtIndex:0];
    
    
    [self.webView makeToast:toastName duration:1.0 position:[CSToastManager defaultPosition]];
    
    CDVPluginResult* pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];
    
    [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
    
}

- (void)upjpush:(CDVInvokedUrlCommand*)command
{
    
    NSString* callbackId = command.callbackId;
    
    NSString *userCode = [command.arguments objectAtIndex:0];
    
    NSDictionary *mess=@{
                         @"userCode":userCode
                         };
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"LoginNotification" object:mess];
    
    
    CDVPluginResult* pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];
    
    [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
    
}


- (void)updateApp:(CDVInvokedUrlCommand*)command
{
    NSString* callbackId = command.callbackId;
    
    NSString *url = [command.arguments objectAtIndex:0];
    
    //@"https://itunes.apple.com/us/app/QQ"
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
    
    CDVPluginResult* pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"ok"];
    
    [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
}

- (void)version:(CDVInvokedUrlCommand*)command
{
    
    NSString* callbackId = command.callbackId;
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *build = [infoDictionary objectForKey:@"CFBundleVersion"];//版本号
    
    CDVPluginResult* pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:build];
    
    [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
    
}

- (void)performBlock:(void(^)())block afterDelay:(NSTimeInterval)delay {
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), block);
}

- (void)uploadFiles:(CDVInvokedUrlCommand*)command
{
    NSString* callbackId = command.callbackId;
    
    NSString *url = [command.arguments objectAtIndex:0];
    
    NSString *fileurl = [command.arguments objectAtIndex:1];
    
    NSString *filename = [command.arguments objectAtIndex:2];
    
    NSString *type = [command.arguments objectAtIndex:3];
    
    NSString *path = [command.arguments objectAtIndex:4];
    
    NSDictionary *parameters=@{@"type":type,@"path":path};
    
    NSString *num = nil;
    NSString *TipText=nil;
    
    if([command.arguments count]==6){
        num = [command.arguments objectAtIndex:5];
        TipText=[NSString stringWithFormat:@"%@%@",@"上传文件",num];
    }else{
        TipText=@"上传文件";
    }
    
    
    MRProgressOverlayView *progressView2 = [MRProgressOverlayView new];
    progressView2.mode = MRProgressOverlayViewModeDeterminateHorizontalBar;
    progressView2.titleLabelText = TipText;
    [self.webView.window addSubview:progressView2];
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:fileurl] name:@"file" fileName:filename mimeType:@"image/jpeg" error:nil];
        
        
        
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    [progressView2 show:YES];
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      // This is not called back on the main queue.
                      // You are responsible for dispatching to the main queue for UI updates
                      dispatch_async(dispatch_get_main_queue(), ^{
                          //Update the progress view
                          
                          
                          [self performBlock:^{
                              [progressView2 setProgress:uploadProgress.fractionCompleted animated:YES];
                          } afterDelay:2.0];
                          NSLog(@"---------%g----",uploadProgress.fractionCompleted);
                          
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      [progressView2 hide:YES];
                      [progressView2 dismiss:YES];
                      CDVPluginResult* pluginresult=nil;
                      if (error) {
                          
                          pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"0"];
                          
                          [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
                          
                          NSLog(@"Error: %@", error);
                      } else {
                          if(num==nil){
                              pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:responseObject];
                          }else{
                              pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:[[NSArray alloc]
                                                                                                                   initWithObjects: responseObject,num,nil]];
                          }
                          
                          [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
                          NSLog(@"%@ %@", response, responseObject);
                      }
                  }];
    
    [uploadTask resume];
    
}

- (void)refresh:(CDVInvokedUrlCommand*)command
{
    
    NSString* status=[command.arguments objectAtIndex:0];
    
    
    if(progressView==nil){
        progressView = [MRProgressOverlayView new];
        progressView.mode = MRProgressOverlayViewModeIndeterminateSmall;
        progressView.titleLabelText = @"加载数据";
        [self.webView.window addSubview:progressView];
        
    }
    
    if([status isEqualToString:@"start"]){
        [progressView show:YES];
        
    }else{
        [progressView hide:YES];
        [progressView dismiss:YES];
        progressView=nil;
    }
    
}

- (void)cropImage:(CDVInvokedUrlCommand*)command
{
    
    NSString* callbackId = command.callbackId;
    
    NSString* path = nil;
    NSInteger isCircle = 0;
    UIImage * photo = nil;
    
    if([command.arguments count]>0){
        path = [command.arguments objectAtIndex:0];
        photo = [[UIImage alloc] initWithContentsOfFile:path];
        isCircle = [[command.arguments objectAtIndex:1] integerValue];
    }
    
    if(photo == nil){
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"0"];
        
        [self.commandDelegate sendPluginResult:pluginResult callbackId:callbackId];
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            if(isCircle==0){
                rskpickerController = [[ZTERSKImageCropViewController alloc] initWithImage:photo cropMode:RSKImageCropModeCircle];
            }else{
                rskpickerController = [[ZTERSKImageCropViewController alloc] initWithImage:photo cropMode:RSKImageCropModeSquare];
            }
            
            rskpickerController.delegate = self;
            rskpickerController.callbackId=callbackId;
            
            [self.viewController presentViewController:rskpickerController animated:YES completion:nil];
        });
        
    }
    
}

- (void)presentViewController:(UIViewController *)viewControllerToPresent
{
    [[self viewController] presentViewController:viewControllerToPresent animated:YES completion:nil];
}

- (void)getImage:(CDVInvokedUrlCommand*)command{
    
    NSString* callbackId = command.callbackId;
    
    NSLog(@"开始执行------------------");
    
    dispatch_async(dispatch_get_main_queue(), ^{
        pickerController = [[ZTEImagePicker alloc] init];
        pickerController.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
        pickerController.allowsEditing = false;
        pickerController.videoQuality=UIImagePickerControllerQualityTypeHigh;
        pickerController.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeMovie,(NSString *) kUTTypeImage,nil];
        pickerController.delegate = self;
        pickerController.callbackId=callbackId;
        
        [self.viewController presentViewController:pickerController animated:YES completion:nil];
    });
    
}

- (void)performDismiss
{
    pickerController = nil;
    [[self viewController] dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    ZTEImagePicker* cameraPicker = (ZTEImagePicker*)picker;
    NSString* callbackId = cameraPicker.callbackId;
    
    [[picker presentingViewController] dismissViewControllerAnimated:YES completion:nil];
    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    NSData* data=nil;
    NSString* filePath=nil;
    CDVPluginResult* pluginresult=nil;
    NSError* err = nil;
    NSString* docsPath = [NSTemporaryDirectory()stringByStandardizingPath];
    
    if([mediaType isEqualToString:(NSString *)kUTTypeImage]){
        
        UIImage *image = info[UIImagePickerControllerOriginalImage];
        data = UIImageJPEGRepresentation(image, 1);
        filePath = [NSString stringWithFormat:@"%@/p_%@.jpg", docsPath, callbackId];
        if([data length]/1024/1024>10){
            [data writeToFile:filePath options:NSAtomicWrite error:&err];
            
            pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"照片大小应小于10兆！"];
        }else{
            [data writeToFile:filePath options:NSAtomicWrite error:&err];
            
            pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:[[NSArray alloc] initWithObjects: filePath,nil]];
        }
        
        
        [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
        
    }else{
        
        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
        
        data = [NSData dataWithContentsOfURL:videoURL];
        
        if([data length]/1024/1024>30){
            pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"视频大小应小于30兆！"];
        }else{
            AVURLAsset *assetvideo = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
            AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:assetvideo];
            
            gen.appliesPreferredTrackTransform = YES;
            gen.requestedTimeToleranceAfter = kCMTimeZero;
            gen.requestedTimeToleranceBefore = kCMTimeZero;
            CMTime time = CMTimeMakeWithSeconds(0.0, 600);
            NSError *error = nil;
            
            CMTime actualTime;
            CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
            UIImage *img = [UIImage imageWithCGImage:image];//[[[UIImage alloc] initWithCGImage:image] autorelease];
            CGImageRelease(image);
            
            NSData* dataImage=UIImageJPEGRepresentation(img, 1);
            
            NSString* filePathImage=[NSString stringWithFormat:@"%@/p_%@.jpg", docsPath, callbackId];
            
            [dataImage writeToFile:filePathImage options:NSAtomicWrite error:&err];
            
            
            filePath = [NSString stringWithFormat:@"%@/p_%@.mov", docsPath, callbackId];
            
            [data writeToFile:filePath options:NSAtomicWrite error:&err];
            
            pluginresult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:[[NSArray alloc] initWithObjects: filePathImage,filePath,nil]];
            
        }
        
        
        
        [self.commandDelegate sendPluginResult:pluginresult callbackId:callbackId];
        
    }
    
    
    [self performDismiss];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    ZTEImagePicker* cameraPicker = (ZTEImagePicker*)picker;
    NSString* callbackId = cameraPicker.callbackId;
    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"error"];
    [self.commandDelegate sendPluginResult:result callbackId:callbackId];
    
    [self performDismiss];
}

#pragma mark - RSKImageCropViewControllerDelegate

- (void)imageCropViewControllerDidCancelCrop:(RSKImageCropViewController *)controller
{
    ZTERSKImageCropViewController* rskpick = (ZTERSKImageCropViewController*)controller;
    NSString* callbackId = rskpick.callbackId;
    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"error"];
    [self.commandDelegate sendPluginResult:result callbackId:callbackId];
    
    
    NSLog(@"开始执行------------------RSKImage_close");
    [self performDismiss];
}

- (void)imageCropViewController:(RSKImageCropViewController *)controller didCropImage:(UIImage *)croppedImage usingCropRect:(CGRect)cropRect
{
    
    NSLog(@"开始执行------------------RSKImage_crop");
    ZTERSKImageCropViewController* rskpick = (ZTERSKImageCropViewController*)controller;
    NSString* callbackId = rskpick.callbackId;
    UIImageWriteToSavedPhotosAlbum(croppedImage, nil, nil, nil);
    
    NSData* data = UIImageJPEGRepresentation(croppedImage, 1);
    
    // write to temp directory and return URI
    NSString* docsPath = [NSTemporaryDirectory()stringByStandardizingPath];   // use file system temporary directory
    NSError* err = nil;
    NSString* filePath = [NSString stringWithFormat:@"%@/photo_crop_%@.jpg", docsPath, callbackId];
    
    [data writeToFile:filePath options:NSAtomicWrite error:&err];
    
    NSLog(@"开始执行------------------RSKImage_crop:callbackId==%@",callbackId);
    NSLog(@"开始执行------------------RSKImage_crop:filePath==%@",filePath);
    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:filePath];
    [self.commandDelegate sendPluginResult:result callbackId:callbackId];
    
    
    [self performDismiss];
    
}
@end
